/*
 * Copyright 2010 Biz-e (info@biz-e.nl)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.biz_e.acl.client.ui.context;

import java.util.HashMap;

import nl.biz_e.acl.shared.model.Context;

import com.google.gwt.user.client.ui.ListBox;
import com.googlecode.objectify.Key;

/**
 * TODO: Write type comment
 * 
 * @author Joost A. Bloemsma
 * 
 */
public class ParentBox extends ListBox {
    private HashMap<String, Integer> keyMap = new HashMap<String, Integer>();

    public ParentBox() {
        super();
    }

    public int getIndex(String ctxId) {
        return keyMap.get(ctxId);
    }

    public int getIndex(Context ctx) {
        return getIndex(ctx.getContextId());
    }

    public void setContexts(Iterable<Context> ctxs) {
        this.clear();
        for (Context ctx : ctxs) {
            this.addContext(ctx);
        }
    }

    @Override
    public void clear() {
        super.clear();
        keyMap.clear();
    }

    public int addContext(Context ctx) {
        String id = ctx.getContextId();
        if (keyMap.containsKey(id))
            return 0;
        this.addItem(ctx.getName(), id);
        int idx = getItemCount() - 1;
        keyMap.put(id, idx);
        return idx;
    }

    public void selectContext(String ctxId) {
        this.setSelectedIndex(this.getIndex(ctxId));
    }

    public void selectContext(Context ctx) {
        this.selectContext(ctx.getContextId());
    }

    public void selectContext(Key<Context> key) {
        // this.selectContext(ctx.getContextId());
    }

    public String getSelectedContextId() {
        return getValue(getSelectedIndex());
    }

}
